<template>
  <div class="city-list">
    <!-- 导航栏 -->
    <nav class="nav">
      <ul class="nav-list">
        <li
          class="nav-list-item"
          v-for="(cities, key) in cities"
          :key="key"
          @click="scrollToSection(key)"
          :class="{ active: activeLetter === key }"
        >
          {{ key }}
        </li>
      </ul>
    </nav>
    <!-- 当前城市 -->
    <div class="area">
      <div class="title">当前城市</div>
      <div class="wrapper">
        <span class="button">{{ cityStore.city }}</span>
      </div>
    </div>
    <!-- 热门城市 -->
    <div class="area">
      <div class="title">热门城市</div>
      <div class="wrapper">
        <span class="button" v-for="city in hotCities" :key="city.id"
          @click="onJump(city)"
        >
        {{ city.name }}</span>
      </div>
    </div>
    <!-- 城市列表区域 -->
    <div
      class="area city-section"
      v-for="(cities, key) in cities"
      :key="key"
      :data-key="key"
    >
      <div class="title">{{ key }}</div>
      <div
        class="city"
        v-for="city in cities"
        :key="city.id"
        @click="onJump(city)"
      >
        {{ city.name }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useCityStore } from '@/stores/cityStore.js'
import { useRouter } from 'vue-router'
const router = useRouter()
const cityStore = useCityStore()
const props = defineProps({
  hotCities: {
    type: Array,
    default: () => []
  },
  cities: {
    type: Object,
    default: () => ({})
  }
})

const sectionRefs = ref([])           // 每个城市区域元素及其key
const activeLetter = ref('')          // 当前高亮字母

// 点击导航栏，滚动到目标区域
function scrollToSection(key) {
  const target = sectionRefs.value.find(item => item.key === key)
  if (target) {
    window.scrollTo({
      top: target.el.offsetTop,
      behavior: 'smooth'
    })
  }
}

// 监听页面滚动，实时更新高亮字母
function onScroll() {
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
  for (let i = sectionRefs.value.length - 1; i >= 0; i--) {
    const { el, key } = sectionRefs.value[i]
    const top = el.getBoundingClientRect().top + window.scrollY
    if (scrollTop + 10 >= top) {
      activeLetter.value = key
      break
    }
  }
}
// 跳转到首页
const onJump = (city) => {
  cityStore.changeCity(city.name)
  router.push('/')
}
// 页面加载时收集所有城市区域的 DOM 元素
onMounted(async () => {
  // 数据是异步加载的，我们用 watch + nextTick 来确保元素存在
  watch(
    () => props.cities, // 监听 props.cities 的变化
    async () => {
      await nextTick() // 等 DOM 渲染
      const elements = document.querySelectorAll('.city-section')
      sectionRefs.value = Array.from(elements).map((el) => ({
        el,
        key: el.dataset.key
      }))
    },
    { immediate: true, deep: true } // 立即执行 + 深度监听
  )
  window.addEventListener('scroll', onScroll)
})

// 页面卸载时移除监听
onUnmounted(() => {
  window.removeEventListener('scroll', onScroll)
})
</script>

<style lang="scss" scoped>
.city-list {
  .nav {
    z-index: 10;
    color: $bgColor;
    font-size:.36rem;
    .nav-list {
      position: fixed;
      top: 3rem;
      right: .2rem;
      .nav-list-item {
        padding: .05rem;
        cursor: default;
          &.active {
            font-weight: bold;
            transform: scale(1.2);
        }
      }
    }
  }
  .area {
    width: 100%;
    background-color: #fff;
    .title {
      box-sizing: border-box;
      width: 100%;
      padding: .15rem .1rem;
      background-color: #eee;
      border-top: 1px solid #ccc;
      border-bottom: 1px solid #ccc;
      color: #666;
      font-size: .36rem;
    }
    .wrapper {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      align-items: center;
      box-sizing: border-box;
      padding: .3rem .1rem .3rem .1rem;
      .button {
        padding: .12rem .6rem;
        border: 1px solid #ccc;
        border-radius: .1rem;
        font-size: .3rem;
        cursor: pointer;
      }
    }
    .city {
      box-sizing: border-box;
      width: 100%;
      border-bottom: 1px solid #ccc;
      padding: .2rem .1rem;
      font-size: .3rem;
      cursor: default;
    }
    .city:last-child {
        border-bottom: none;
      }
  }
}
</style>
